import MeasureManager from './measureManager'
import BasemapManager from './basemapManager'
import {
  mosaicShader,
  rainShader,
  snowShader
} from '@/utils/shader/shaders'
import { Message } from 'element-ui'
import { min, max } from 'lodash'
import * as turf from '@turf/turf'

export default class Tool {
  constructor(viewer, cesium) {
    this._viewer = viewer
    this._Cesium = cesium
    this._basemapManager = null
    this._fog = null // 天气 雾
    this._skyline = null // 天际线
    this._measure = null // 测量工具
    this._sightline = null // 通视分析
    this._viewfield = null // 视域分析
    this._underground = null // 地下模式
    this._style = {
      stages: viewer.scene.postProcessStages,
      bloom: undefined,
      BrightnessStage: undefined,
      NightVisionStage: undefined,
      BlackAndWhiteStage: undefined,
      MosaicStage: undefined,
      DepthOfFieldStage: undefined
    }
    this._weather = {
      fog: null,
      snow: null,
      snowCover: null,
      rain: null
    }

    // // 挖地
    // this.terrainClipPlan = new mars3d.analysi.TerrainClipPlan(
    //   {
    //     viewer: this._viewer,
    //     enable: false,
    //     height: 50, // 高度
    //     splitNum: 50, // wall边界插值数
    //     wallImg: 'img/piping/excavate_side_min.jpg', // 边界墙材质
    //     bottomImg: 'img/piping/excavate_bottom_min.jpg' // 底部区域材质
    //   }
    // )
    // // 漫游
    // viewer.mars.keyboardRoam.moveStep = 0.1
    // viewer.mars.keyboardRoam.dirStep = 1
    // viewer.mars.keyboardRoam.rotateStep = 0.3
    // viewer.mars.keyboardRoam.minPitch = 0
    // viewer.mars.keyboardRoam.maxPitch = 1
    // viewer.mars.keyboardRoam.enable = false
  }

  get measure() {
    if (!this._measure) {
      this._measure = new MeasureManager(this._viewer)
    }
    return this._measure
  }

  get sunshine() {
    return {
      destroy: () => {
        this._viewer.scene.enableLighting = false
        this._viewer.scene.globe.enableLighting = false
        this._viewer.shadows = false
        this._viewer.scene.sun.show = false
        this._viewer.clock.shouldAnimate = false
        this._viewer.clock.currentTime =
          Cesium.JulianDate.fromDate(
            new Date(2020, 10, 1, 12)
          )
        this._viewer.clock.stopTime =
          this._viewer.clock.currentTime
        this._viewer.clock.onTick._listeners.forEach(
          (fn) => {
            this._viewer.clock.onTick.removeEventListener(
              fn
            )
          }
        )
      },
      clear: () => {
        this._viewer.scene.enableLighting = false
        this._viewer.scene.globe.enableLighting = false
        this._viewer.shadows = false
        this._viewer.scene.sun.show = false
        this._viewer.clock.shouldAnimate = false
        this._viewer.clock.currentTime =
          Cesium.JulianDate.fromDate(
            new Date(2020, 10, 1, 12)
          )
        this._viewer.clock.stopTime =
          this._viewer.clock.currentTime
        this._viewer.clock.onTick._listeners.forEach(
          (fn) => {
            this._viewer.clock.onTick.removeEventListener(
              fn
            )
          }
        )
      },
      init: ({ startTime, stopTime, currentTime }) => {
        this._viewer.scene.enableLighting = true
        this._viewer.scene.globe.enableLighting = true
        this._viewer.shadows = true
        this._viewer.scene.sun.show = true
        this._viewer.clock.startTime = startTime
        this._viewer.clock.stopTime = stopTime
        this._viewer.clock.currentTime = currentTime
        this._viewer.clock.clockRange =
          this._Cesium.ClockRange.LOOP_STOP
        this._viewer.clock.clockStep =
          this._Cesium.ClockStep.SYSTEM_CLOCK_MULTIPLIER
        this._viewer.clock.multiplier = 3200
      },
      start: ({ startTime, stopTime, currentTime }) => {
        this._viewer.scene.enableLighting = true
        this._viewer.scene.globe.enableLighting = true
        this._viewer.shadows = true
        this._viewer.scene.sun.show = true
        this._viewer.clock.startTime = startTime
        this._viewer.clock.stopTime = stopTime
        this._viewer.clock.currentTime = currentTime
        this._viewer.clock.clockRange =
          this._Cesium.ClockRange.LOOP_STOP
        this._viewer.clock.clockStep =
          this._Cesium.ClockStep.SYSTEM_CLOCK_MULTIPLIER
        this._viewer.clock.multiplier = 3200
        this._viewer.clock.shouldAnimate = true
      },
      pause: () => {
        this._viewer.clock.stopTime =
          this._viewer.clock.currentTime
        this._viewer.clock.shouldAnimate = false
      },
      updateCurrentTime: (currentTime) => {
        this._viewer.clock.currentTime = currentTime
      },
      onClock: (clockFn) => {
        this._viewer.clock.onTick.addEventListener(clockFn)
      },
      // hasListener: () => {
      //   console.log('events:', this._viewer.clock.onTick)
      //   return (this._viewer.clock.onTick._listeners.length !== 2)
      // },
      offClock: (clockFn) => {
        this._viewer.clock.onTick.removeEventListener(
          clockFn
        )
      }
    }
  }

  get brightness() {
    return {
      getBrightness: () => {
        if (
          this._viewer.scene.brightness &&
          this._viewer.scene.brightness.uniforms
        ) {
          return this._viewer.scene.brightness.uniforms
            .brightness
        }
        return 1
      },
      setBrightness: (brightness) => {
        const stages = this._viewer.scene.postProcessStages
        if (!this._viewer.scene.brightness) {
          this._viewer.scene.brightness = stages.add(
            Cesium.PostProcessStageLibrary.createBrightnessStage()
          )
        }
        this._viewer.scene.brightness.enabled = true
        this._viewer.scene.brightness.uniforms.brightness =
          Number(brightness)
        console.log(
          '修改后',
          this._viewer.scene.brightness.uniforms.brightness
        )
      }
    }
  }

  get skyline() {
    return {
      destroy: () => {
        if (this._skyline) {
          this._skyline.clear()
          this._skyline = null
        }
      },
      pick: () => {
        if (!this._skyline) {
          this._skyline = new Cesium.Skyline(this.scene)
        }
        document.getElementById(
          'skyLineChart'
        ).style.display = 'none'
        const cartographic =
          this.scene.camera.positionCartographic
        const longitude = Cesium.Math.toDegrees(
          cartographic.longitude
        )
        const latitude = Cesium.Math.toDegrees(
          cartographic.latitude
        )
        const height = cartographic.height

        // 天际线分析的视口位置设置成当前相机位置
        this._skyline.viewPosition = [
          longitude,
          latitude,
          height
        ]
        // 设置俯仰和方向
        this._skyline.pitch = Cesium.Math.toDegrees(
          this.scene.camera.pitch
        )
        this._skyline.direction = Cesium.Math.toDegrees(
          this.scene.camera.heading
        )
        this._skyline.radius = 10000 // 天际线分析半径设置为10000米
        this._skyline.build()
        Message.success('天际线提取完成')
      },
      start: () => {
        if (!this._skyline) {
          throw new Error('请先提取天际线')
        }
        // 获取二维天际线对象
        const object = this._skyline.getSkyline2D()
        // 用echarts绘制二维天际线
        const myChart = echarts.init(
          document.getElementById('skyLineChart')
        )
        const option = {
          backgroundColor: 'rgba(255,255,255,0.5)',
          title: {
            text: '二维天际线'
          },

          tooltip: {
            trigger: 'axis'
          },

          calculable: true,
          xAxis: [
            {
              type: 'category',
              boundaryGap: false,
              data: object.x,
              show: false
            }
          ],

          yAxis: [
            {
              type: 'value',
              min: 0,
              max: 1
            }
          ],

          series: [
            {
              name: '',
              type: 'line',
              data: object.y
            }
          ]
        }
        myChart.setOption(option)
        document.getElementById(
          'skyLineChart'
        ).style.display = 'block'
      },
      clear: () => {
        if (this._skyline) {
          this._skyline.clear()
          this._skyline = null
        }
      }
    }
  }

  get sightline() {
    const self = this
    return {
      handlerPoint: null,
      handler: null,
      addViewFlag: false, // 当前点击状态是否是 添加观察点
      addTargetFlag: false, // 当前点击状态是否是 添加目标点
      num: 0, // 添加的目标点的点号
      couldRemove: false, // 是否能移除目标点
      Cartesian2toDegrees(position) {
        const cartographic =
          Cesium.Cartographic.fromCartesian(position)
        const longitude = Cesium.Math.toDegrees(
          cartographic.longitude
        )
        const latitude = Cesium.Math.toDegrees(
          cartographic.latitude
        )
        const height = cartographic.height

        return [longitude, latitude, height]
      },
      addTarget(CartesianPosition) {
        if (
          this.addViewFlag === false &&
          this.addTargetFlag
        ) {
          this.num += 1
          // 将获取的点的位置转化成经纬度
          const cartographic = this.Cartesian2toDegrees(
            CartesianPosition
          )
          // 添加目标点
          const name = 'point' + this.num
          // const flag =
          self._sightline.addTargetPoint({
            position: cartographic,
            name: name
          })
          this.couldRemove = true
        }
      },
      init() {
        const that = this
        if (!self._sightline) {
          self._sightline = new Cesium.Sightline(self.scene)

          this.handlerPoint = new Cesium.DrawHandler(
            self._viewer,
            Cesium.DrawMode.Point
          )
          this.handlerPoint.drawEvt.addEventListener(
            function (result) {
              // 添加观察点
              if (that.addViewFlag) {
                // const point = result.object
                // point.show = false
                const position = result.object.position
                // 将获取的点的位置转化成经纬度
                // 设置观察点
                self._sightline.viewPosition =
                  that.Cartesian2toDegrees(position)
                that.addViewFlag = false
              }
              that.handlerPoint.deactivate()
            }
          )

          this.handler = new Cesium.ScreenSpaceEventHandler(
            self.canvas
          )
        }
      },
      destroy() {
        this.clear()
        self._sightline = null
      },
      clear() {
        this.addViewFlag = false
        this.addTargetFlag = false
        if (this.handlerPoint) {
          this.handlerPoint.clear()
        }
        this.num = 0
        self._viewer.entities.removeAll()
        if (self._sightline && this.couldRemove) {
          self._sightline.removeAllTargetPoint()
          this.couldRemove = false
        }
        self._viewer.enableCursorStyle = true
      },
      observe() {
        this.addViewFlag = true
        if (this.handlerPoint.active) {
          return
        }
        self._viewer.entities.removeAll()
        if (this.couldRemove) {
          self._sightline.removeAllTargetPoint()
        }
        this.handlerPoint.activate()

        if (this.addViewFlag || this.addTargetFlag) {
          self._viewer.enableCursorStyle = false
          self._viewer._element.style.cursor = ''
        }
      },
      target() {
        this.addViewFlag = false
        this.addTargetFlag = true
        const that = this

        if (this.addViewFlag || this.addTargetFlag) {
          self._viewer.enableCursorStyle = false
          self._viewer._element.style.cursor = ''
        }

        // 鼠标点击事件，添加点
        this.handler.setInputAction(function (e) {
          const position = self.scene.pickPosition(
            e.position
          )
          that.addTarget(position)
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

        // 鼠标移动事件，更新点
        this.handler.setInputAction(function (evt) {
          // 鼠标移动，更新最后一次添加的目标点的位置
          const position = self.scene.pickPosition(
            evt.endPosition
          )

          if (that.num > 0) {
            self._sightline.removeTargetPoint('point0')

            const cartographic =
              that.Cartesian2toDegrees(position)

            // const flag =
            self._sightline.addTargetPoint({
              position: cartographic,
              name: 'point0'
            })
          }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

        // 鼠标右键事件，结束
        this.handler.setInputAction(function () {
          self._viewer.enableCursorStyle = true
          that.handler.removeInputAction(
            Cesium.ScreenSpaceEventType.MOUSE_MOVE
          )
          that.handler.removeInputAction(
            Cesium.ScreenSpaceEventType.LEFT_CLICK
          )
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
      }
    }
  }

  get viewer() {
    return this._viewer
  }

  get viewfield() {
    const self = this
    return {
      handler: null,
      pointHandler: null,
      viewPosition: null,
      destroy() {
        if (self._viewfield) {
          self.viewer.entities.removeAll()
          self.scene.viewFlag = true
          self._viewfield.distance = 0.1
          this.pointHandler.clear()
          this.handler = null
          self._viewfield = null
        }
      },
      clear() {
        if (self._viewfield) {
          self.viewer.entities.removeAll()
          self._viewfield.distance = 0.1
          this.pointHandler.clear()
          self.scene.viewFlag = true
          self._viewfield = null
        }
      },
      start() {
        if (!self._viewfield) {
          self._viewfield = new Cesium.ViewShed3D(
            self.scene
          )
          this.pointHandler = new Cesium.DrawHandler(
            self.viewer,
            Cesium.DrawMode.Point
          )

          this.handler = new Cesium.ScreenSpaceEventHandler(
            self.scene.canvas
          )
          // 鼠标移动时间回调
          this.handler.setInputAction(function (e) {
            // 若此标记为false，则激活对可视域分析对象的操作
            if (!self.scene.viewFlag) {
              // 获取鼠标屏幕坐标,并将其转化成笛卡尔坐标
              const position = e.endPosition
              const last = self.scene.pickPosition(position)

              // 计算该点与视口位置点坐标的距离
              const distance = Cesium.Cartesian3.distance(
                self.viewPosition,
                last
              )

              if (distance > 0) {
                // 将鼠标当前点坐标转化成经纬度
                const cartographic =
                  Cesium.Cartographic.fromCartesian(last)
                const longitude = Cesium.Math.toDegrees(
                  cartographic.longitude
                )
                const latitude = Cesium.Math.toDegrees(
                  cartographic.latitude
                )
                const height = cartographic.height
                // 通过该点设置可视域分析对象的距离及方向
                self._viewfield.setDistDirByPoint([
                  longitude,
                  latitude,
                  height
                ])
              }
            }
          }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

          this.handler.setInputAction(function (e) {
            // 鼠标右键事件回调，不再执行鼠标移动事件中对可视域的操作
            self.scene.viewFlag = true
          }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)

          this.pointHandler.drawEvt.addEventListener(
            function (result) {
              const point = result.object
              const position = point.position
              self.viewPosition = position

              // 将获取的点的位置转化成经纬度
              const cartographic =
                Cesium.Cartographic.fromCartesian(position)
              const longitude = Cesium.Math.toDegrees(
                cartographic.longitude
              )
              const latitude = Cesium.Math.toDegrees(
                cartographic.latitude
              )
              const height = cartographic.height + 1.8
              point.position =
                Cesium.Cartesian3.fromDegrees(
                  longitude,
                  latitude,
                  height
                )

              if (self.scene.viewFlag) {
                // 设置视口位置
                self._viewfield.viewPosition = [
                  longitude,
                  latitude,
                  height
                ]
                self._viewfield.build()
                // 将标记置为false以激活鼠标移动回调里面的设置可视域操作
                self.scene.viewFlag = false
              }
            }
          )
        }
        if (this.pointHandler.active) {
          return
        }
        // 先清除之前的可视域分析
        self._viewer.entities.removeAll()
        self._viewfield.distance = 0.1
        self.scene.viewFlag = true

        // 激活绘制点类
        this.pointHandler.activate()
        // self.scene.viewFlag = false
      }
    }
  }

  get basemapManager() {
    if (!this._basemapManager) {
      this._basemapManager = new BasemapManager(
        this._viewer,
        this._Cesium
      )
    }
    return this._basemapManager
  }

  // get basemap() {
  //   const self = this
  //   const basemapList = [
  //     {
  //       pkid: '-1',
  //       serviceName: '无底图',
  //       isDefault: false,
  //       type: null,
  //       showTerrain: false,
  //       fileUrl: '',
  //       resourceMapBaseServiceInfos: []
  //     }
  //   ]
  //   return {
  //     async getList() {
  //       if (basemapList.length === 1) {
  //         const result = await mapQuery({
  //           pageIndex: 1,
  //           pageSize: 100
  //         })
  //         if (result.success) {
  //           result.data.list.map((item) => {
  //             item.resourceMapBaseServiceInfos = []
  //             return item
  //           })
  //           await this._getChildList(result.data.list)
  //         }
  //       }
  //       return basemapList
  //     },
  //     async _getChildList(parentList) {
  //       await parentList.map(async (item, index) => {
  //         await mapServiceQuery(item.pkid).then((res) => {
  //           if (res.success) {
  //             item.resourceMapBaseServiceInfos =
  //               res.data.resourceMapBaseServiceInfos.sort(
  //                 (a, b) => a.orderIndex - b.orderIndex
  //               )
  //             basemapList.push({
  //               pkid: item.pkid,
  //               name: item.name,
  //               isDefault: item.isDefault,
  //               type: null,
  //               showTerrain: false,
  //               fileUrl: item.filePath,
  //               resourceMapBaseServiceInfos:
  //                 item.resourceMapBaseServiceInfos
  //             })
  //             if (item.isDefault === 1) {
  //               const find =
  //                 item.resourceMapBaseServiceInfos.find(
  //                   (temp) => temp.isDefault === 1
  //                 )
  //               let tempPkid = ''
  //               if (find) {
  //                 tempPkid = find.pkid
  //               } else {
  //                 tempPkid =
  //                   item.resourceMapBaseServiceInfos[0].pkid
  //               }
  //               this.currentIndex = index + 1
  //               this.serviceSwitch(tempPkid)
  //             }
  //           }
  //         })
  //       })
  //     },
  //     currentIndex: 0,
  //     currentServiceIndex: 0,
  //     mapService: [],
  //     getCurrentIndex() {
  //       return this.currentIndex
  //     },
  //     getCurrentServiceIndex() {
  //       return this.currentServiceIndex
  //     },
  //     getMapService() {
  //       return this.mapService
  //     },
  //     serviceSwitch(id) {
  //       if (this.currentServiceIndex !== 0) {
  //         // 如果当前不是无底图，则清除之前的底图
  //         const previousItem =
  //           basemapList[this.currentIndex]
  //         let data = {}
  //         const find =
  //           previousItem.resourceMapBaseServiceInfos.find(
  //             (item) => {
  //               return (
  //                 item.pkid === this.currentServiceIndex
  //               )
  //             }
  //           )
  //         if (find) {
  //           data = find
  //         }
  //         if (data.serviceUrl) {
  //           if (data.serviceType === 23) {
  //             self._viewer.scene.removeVectorTilesMap(
  //               data.serviceName
  //             )
  //           } else {
  //             if (data.serviceType !== 27) {
  //               const firstImagery =
  //                 self._viewer.scene.imageryLayers.get(0)
  //               self._viewer.scene.imageryLayers.remove(
  //                 firstImagery,
  //                 true
  //               )
  //             } else {
  //               // 三维
  //               if (data.name) {
  //                 data.name.forEach((nameItem, index) => {
  //                   if (!nameItem) {
  //                     if (
  //                       data.layers[index].imageryProvider
  //                     ) {
  //                       self._viewer.scene.imageryLayers.remove(
  //                         data.layers[index]
  //                       )
  //                     } else if (
  //                       data.layers[index]._iserrainZ
  //                     ) {
  //                       self._viewer.terrainProvider =
  //                         new Cesium.EllipsoidTerrainProvider(
  //                           {}
  //                         )
  //                     }
  //                   } else {
  //                     self._viewer.scene.layers.remove(
  //                       nameItem
  //                     )
  //                   }
  //                 })
  //               }
  //             }
  //           }
  //         }
  //       }
  //       const item = basemapList[this.currentIndex]
  //       const find = item.resourceMapBaseServiceInfos.find(
  //         (temp) => temp.pkid === id
  //       )
  //       let data2 = {}
  //       if (find) {
  //         this.currentServiceIndex = find.pkid
  //         data2 = find
  //         if (find.terrainUrl) {
  //           self._viewer.terrainProvider =
  //             new Cesium.CesiumTerrainProvider({
  //               url: find.terrainUrl,
  //               requestWaterMask: true, // 开启法向量
  //               requestVertexNormals: true, // 开启水面特效
  //               isSct: true
  //             })
  //           item.showTerrain = true
  //         } else {
  //           self._viewer.terrainProvider =
  //             new Cesium.EllipsoidTerrainProvider()
  //           item.showTerrain = false
  //         }
  //       }
  //       this.mapService = data2
  //       // debugger
  //       if (globalBaseMap['supermap-container'] === this) {
  //         New.$emit('mapIndex', {
  //           list: item.resourceMapBaseServiceInfos,
  //           active: data2
  //         })
  //       } else if (
  //         globalBaseMap['compare-container'] === this
  //       ) {
  //         New.$emit('mapCompareIndex', {
  //           list: item.resourceMapBaseServiceInfos,
  //           active: data2
  //         })
  //       }
  //       if (data2.serviceUrl) {
  //         switch (data2.serviceType) {
  //           case 21:
  //             // WMTS
  //             self._viewer.scene.imageryLayers.addImageryProvider(
  //               new Cesium.WebMapTileServiceImageryProvider(
  //                 {
  //                   url: data2.serviceUrl,
  //                   layer: data2.serviceName,
  //                   style: 'default',
  //                   tileMatrixSetID: 'default028mm'
  //                 }
  //               ),
  //               0
  //             )
  //             break
  //           case 22:
  //             // XYZ Tiles
  //             self._viewer.scene.imageryLayers.addImageryProvider(
  //               new Cesium.WebMapTileServiceImageryProvider(
  //                 {
  //                   url: data2.serviceUrl,
  //                   layer: data2.serviceName,
  //                   style: 'default',
  //                   tileMatrixSetID: 'default028mm'
  //                 }
  //               ),
  //               0
  //             )
  //             break
  //           case 23:
  //             // 矢量
  //             self._viewer.scene.addVectorTilesMap({
  //               url: data2.serviceUrl,
  //               layer: data2.serviceName
  //             })
  //             break
  //           case 24:
  //             // WMS
  //             self._viewer.scene.imageryLayers.addImageryProvider(
  //               new Cesium.WebMapServiceImageryProvider({
  //                 url: data2.serviceUrl,
  //                 layers: data2.serviceName
  //               }),
  //               0
  //             )
  //             break
  //           case 25:
  //             // ArcGIS
  //             self._viewer.scene.imageryLayers.addImageryProvider(
  //               new Cesium.ArcGisMapServerImageryProvider({
  //                 url: data2.serviceUrl
  //               }),
  //               0
  //             )
  //             break
  //           case 26:
  //             // REST
  //             self._viewer.scene.imageryLayers.addImageryProvider(
  //               new Cesium.SuperMapImageryProvider({
  //                 url: data2.serviceUrl,
  //                 isSct: true
  //                 // minimumLevel: 0,
  //                 // maximumLevel: 24
  //               }),
  //               0
  //             )
  //             break
  //           case 27:
  //             // 三维
  //             let url, name
  //             if (
  //               data2.serviceUrl.indexOf(
  //                 '/realspace/datas/'
  //               ) !== -1
  //             ) {
  //               url = data2.serviceUrl
  //               name = data2.serviceName
  //               const promise =
  //                 self._viewer.scene.addS3MTilesLayerByScp(
  //                   url + '/config',
  //                   {
  //                     autoSetView: false,
  //                     name: name,
  //                     cullEnabled: true
  //                   }
  //                 )
  //               Cesium.when(promise, (layer) => {
  //                 if (layer) {
  //                   // if (data2.serviceUrl.indexOf('3D-T0102_XiangMuZhanShiZhuanTiTu_2/rest/realspace/scenes/T0102_%E9%A1%B9%E7%9B%AE%E5%B1%95%E7%A4%BA%E4%B8%93%E9%A2%98%E5%9B%BE_2') !== -1) {
  //                   //   layer.isOverlapDisplayed = false
  //                   // } else {
  //                   //   layer.isOverlapDisplayed = true
  //                   // }
  //                   layer.clearMemoryImmediately = true
  //                   layer.residentRootTile = false
  //                   layer.isOverlapDisplayed = false
  //                   // layer.indexedDBSetting.isGeoTilesRootNodeSave = true
  //                   data2.name = [name]
  //                   data2.layer = [layer]
  //                 } else {
  //                   console.error('添加失败')
  //                 }
  //               })
  //             } else if (
  //               data2.serviceUrl.indexOf(
  //                 '/realspace/scenes/'
  //               ) === -1
  //             ) {
  //               url = data2.serviceUrl
  //               name = undefined
  //               const promise = self._viewer.scene.open(
  //                 url,
  //                 name,
  //                 { autoSetView: false }
  //               )
  //               Cesium.when(promise, (layers) => {
  //                 if (layers) {
  //                   const realName = []
  //                   layers.forEach((layer) => {
  //                     // if (data2.serviceUrl.indexOf('3D-T0102_XiangMuZhanShiZhuanTiTu_2/rest/realspace/scenes/T0102_%E9%A1%B9%E7%9B%AE%E5%B1%95%E7%A4%BA%E4%B8%93%E9%A2%98%E5%9B%BE_2') !== -1) {
  //                     //   layer.isOverlapDisplayed = false
  //                     // } else {
  //                     //   layer.isOverlapDisplayed = true
  //                     // }
  //                     layer.clearMemoryImmediately = true
  //                     layer.residentRootTile = false
  //                     layer.isOverlapDisplayed = false
  //                     realName.push(layer.name)
  //                     if (layer.imageryProvider) {
  //                       self._viewer.imageryLayers.lowerToBottom(
  //                         layer
  //                       )
  //                     }
  //                   })
  //                   data2.name = realName
  //                   data2.layers = layers
  //                 } else {
  //                   console.error('添加失败')
  //                 }
  //               })
  //             } else {
  //               url = data2.serviceUrl.substring(
  //                 0,
  //                 data2.serviceUrl.indexOf('/scenes')
  //               )
  //               name = decodeURI(
  //                 data2.serviceUrl.substring(
  //                   data2.serviceUrl.indexOf('/scenes/') +
  //                     '/scenes/'.length
  //                 )
  //               )
  //               const promise = self._viewer.scene.open(
  //                 url,
  //                 name,
  //                 { autoSetView: false }
  //               )
  //               Cesium.when(promise, (layers) => {
  //                 if (layers) {
  //                   const realName = []
  //                   layers.forEach((layer) => {
  //                     // if (data2.serviceUrl.indexOf('3D-T0102_XiangMuZhanShiZhuanTiTu_2/rest/realspace/scenes/T0102_%E9%A1%B9%E7%9B%AE%E5%B1%95%E7%A4%BA%E4%B8%93%E9%A2%98%E5%9B%BE_2') !== -1) {
  //                     //   layer.isOverlapDisplayed = false
  //                     // } else {
  //                     //   layer.isOverlapDisplayed = true
  //                     // }
  //                     layer.clearMemoryImmediately = true
  //                     layer.residentRootTile = false
  //                     layer.isOverlapDisplayed = false
  //                     realName.push(layer.name)
  //                     if (layer.imageryProvider) {
  //                       self._viewer.imageryLayers.lowerToBottom(
  //                         layer
  //                       )
  //                     }
  //                   })
  //                   data2.name = realName
  //                   data2.layers = layers
  //                 } else {
  //                   console.error('添加失败')
  //                 }
  //               })
  //             }
  //             break
  //           case 28:
  //             const queryParams = getQueryParams(
  //               data2.serviceUrl
  //             )
  //             console.log(queryParams)
  //             // let mapStyle = ''
  //             // switch (queryParams.T) {
  //             //   case 'img_c':
  //             //     mapStyle = Cesium.TiandituMapsStyle.IMG_C
  //             //     break
  //             //   default:
  //             //     break
  //             // }
  //             self._viewer.scene.imageryLayers.addImageryProvider(
  //               new Cesium.TiandituImageryProvider({
  //                 // mapStyle: mapStyle,
  //                 mapStyle: queryParams.T,
  //                 token: queryParams.tk
  //               }),
  //               0
  //             )
  //             break
  //           default:
  //             break
  //         }
  //         self._viewer.scene.requestRender()
  //       }
  //     },
  //     switch(index) {
  //       if (this.currentIndex !== 0) {
  //         // 如果当前不是无底图，则清除之前的底图
  //         const previousItem =
  //           basemapList[this.currentIndex]
  //         let data = {}
  //         const find =
  //           previousItem.resourceMapBaseServiceInfos.find(
  //             (item) => {
  //               return (
  //                 item.pkid === this.currentServiceIndex
  //               )
  //             }
  //           )
  //         if (find) {
  //           data = find
  //         }
  //         if (data.serviceUrl) {
  //           if (data.serviceType === 23) {
  //             self._viewer.scene.removeVectorTilesMap(
  //               data.serviceName
  //             )
  //           } else {
  //             if (data.serviceType !== 27) {
  //               const firstImagery =
  //                 self._viewer.scene.imageryLayers.get(0)
  //               self._viewer.scene.imageryLayers.remove(
  //                 firstImagery,
  //                 true
  //               )
  //             } else {
  //               // 三维
  //               if (data.name) {
  //                 data.name.forEach((nameItem, index) => {
  //                   if (!nameItem) {
  //                     if (
  //                       data.layers[index].imageryProvider
  //                     ) {
  //                       self._viewer.scene.imageryLayers.remove(
  //                         data.layers[index]
  //                       )
  //                     } else if (
  //                       data.layers[index]._iserrainZ
  //                     ) {
  //                       self._viewer.terrainProvider =
  //                         new Cesium.EllipsoidTerrainProvider(
  //                           {}
  //                         )
  //                     }
  //                   } else {
  //                     self._viewer.scene.layers.remove(
  //                       nameItem
  //                     )
  //                   }
  //                 })
  //               }
  //             }
  //           }
  //         }
  //       }
  //       this.currentIndex = index
  //       const item = basemapList[index]
  //       if (item.pkid === '-1') {
  //         this.currentServiceIndex = 0
  //         // debugger
  //         if (
  //           globalBaseMap['supermap-container'] === this
  //         ) {
  //           New.$emit('mapIndex', {
  //             list: [],
  //             active: {}
  //           })
  //         } else if (
  //           globalBaseMap['compare-container'] === this
  //         ) {
  //           New.$emit('mapCompareIndex', {
  //             list: [],
  //             active: {}
  //           })
  //         }
  //         return
  //       }
  //       const find = item.resourceMapBaseServiceInfos.find(
  //         (item) => {
  //           return item.isDefault
  //         }
  //       )
  //       let data2 = {}
  //       if (find) {
  //         this.currentServiceIndex = find.pkid
  //         data2 = find
  //       } else {
  //         data2 = item.resourceMapBaseServiceInfos[0]
  //         this.currentServiceIndex = data2.pkid
  //       }
  //       if (data2.terrainUrl) {
  //         self._viewer.terrainProvider =
  //           new Cesium.CesiumTerrainProvider({
  //             url: data2.terrainUrl,
  //             requestWaterMask: true, // 开启法向量
  //             requestVertexNormals: true, // 开启水面特效
  //             isSct: true
  //           })
  //         item.showTerrain = true
  //       } else {
  //         self._viewer.terrainProvider =
  //           new Cesium.EllipsoidTerrainProvider()
  //         item.showTerrain = false
  //       }
  //       // debugger
  //       if (globalBaseMap['supermap-container'] === this) {
  //         New.$emit('mapIndex', {
  //           list: item.resourceMapBaseServiceInfos,
  //           active: data2
  //         })
  //       } else if (
  //         globalBaseMap['compare-container'] === this
  //       ) {
  //         New.$emit('mapCompareIndex', {
  //           list: item.resourceMapBaseServiceInfos,
  //           active: data2
  //         })
  //       }
  //       this.mapService = data2
  //       if (data2.serviceUrl) {
  //         switch (data2.serviceType) {
  //           case 21:
  //             // WMTS
  //             self._viewer.scene.imageryLayers.addImageryProvider(
  //               new Cesium.WebMapTileServiceImageryProvider(
  //                 {
  //                   url: data2.serviceUrl,
  //                   layer: data2.serviceName,
  //                   style: 'default',
  //                   tileMatrixSetID: 'default028mm'
  //                 }
  //               ),
  //               0
  //             )
  //             break
  //           case 22:
  //             // XYZ Tiles
  //             self._viewer.scene.imageryLayers.addImageryProvider(
  //               new Cesium.WebMapTileServiceImageryProvider(
  //                 {
  //                   url: data2.serviceUrl,
  //                   layer: data2.serviceName,
  //                   style: 'default',
  //                   tileMatrixSetID: 'default028mm'
  //                 }
  //               ),
  //               0
  //             )
  //             break
  //           case 23:
  //             // 矢量
  //             self._viewer.scene.addVectorTilesMap({
  //               url: data2.serviceUrl,
  //               layer: data2.serviceName
  //             })
  //             break
  //           case 24:
  //             // WMS
  //             self._viewer.scene.imageryLayers.addImageryProvider(
  //               new Cesium.WebMapServiceImageryProvider({
  //                 url: data2.serviceUrl,
  //                 layers: data2.serviceName
  //               }),
  //               0
  //             )
  //             break
  //           case 25:
  //             // ArcGIS
  //             self._viewer.scene.imageryLayers.addImageryProvider(
  //               new Cesium.ArcGisMapServerImageryProvider({
  //                 url: data2.serviceUrl
  //               }),
  //               0
  //             )
  //             break
  //           case 26:
  //             // REST
  //             self._viewer.scene.imageryLayers.addImageryProvider(
  //               new Cesium.SuperMapImageryProvider({
  //                 url: data2.serviceUrl,
  //                 isSct: true
  //                 // minimumLevel: 0,
  //                 // maximumLevel: 24
  //               }),
  //               0
  //             )
  //             break
  //           case 27:
  //             // 三维
  //             let url, name
  //             if (
  //               data2.serviceUrl.indexOf(
  //                 '/realspace/datas/'
  //               ) !== -1
  //             ) {
  //               url = data2.serviceUrl
  //               name = data2.serviceName
  //               const promise =
  //                 self._viewer.scene.addS3MTilesLayerByScp(
  //                   url + '/config',
  //                   {
  //                     autoSetView: false,
  //                     name: name,
  //                     cullEnabled: true
  //                   }
  //                 )
  //               Cesium.when(promise, (layer) => {
  //                 if (layer) {
  //                   // if (data2.serviceUrl.indexOf('3D-T0102_XiangMuZhanShiZhuanTiTu_2/rest/realspace/scenes/T0102_%E9%A1%B9%E7%9B%AE%E5%B1%95%E7%A4%BA%E4%B8%93%E9%A2%98%E5%9B%BE_2') !== -1) {
  //                   //   layer.isOverlapDisplayed = false
  //                   // } else {
  //                   //   layer.isOverlapDisplayed = true
  //                   // }
  //                   layer.clearMemoryImmediately = true
  //                   layer.residentRootTile = false
  //                   layer.isOverlapDisplayed = false
  //                   // layer.indexedDBSetting.isGeoTilesRootNodeSave = true
  //                   data2.name = [name]
  //                   data2.layer = [layer]
  //                 } else {
  //                   console.error('添加失败')
  //                 }
  //               })
  //             } else if (
  //               data2.serviceUrl.indexOf(
  //                 '/realspace/scenes/'
  //               ) === -1
  //             ) {
  //               url = data2.serviceUrl
  //               name = undefined
  //               const promise = self._viewer.scene.open(
  //                 url,
  //                 name,
  //                 { autoSetView: false }
  //               )
  //               Cesium.when(promise, (layers) => {
  //                 if (layers) {
  //                   const realName = []
  //                   layers.forEach((layer) => {
  //                     // if (data2.serviceUrl.indexOf('3D-T0102_XiangMuZhanShiZhuanTiTu_2/rest/realspace/scenes/T0102_%E9%A1%B9%E7%9B%AE%E5%B1%95%E7%A4%BA%E4%B8%93%E9%A2%98%E5%9B%BE_2') !== -1) {
  //                     //   layer.isOverlapDisplayed = false
  //                     // } else {
  //                     //   layer.isOverlapDisplayed = true
  //                     // }
  //                     layer.clearMemoryImmediately = true
  //                     layer.residentRootTile = false
  //                     layer.isOverlapDisplayed = false
  //                     realName.push(layer.name)
  //                     if (layer.imageryProvider) {
  //                       self._viewer.imageryLayers.lowerToBottom(
  //                         layer
  //                       )
  //                     }
  //                   })
  //                   data2.name = realName
  //                   data2.layers = layers
  //                 } else {
  //                   console.error('添加失败')
  //                 }
  //               })
  //             } else {
  //               url = data2.serviceUrl.substring(
  //                 0,
  //                 data2.serviceUrl.indexOf('/scenes')
  //               )
  //               name = decodeURI(
  //                 data2.serviceUrl.substring(
  //                   data2.serviceUrl.indexOf('/scenes/') +
  //                     '/scenes/'.length
  //                 )
  //               )
  //               const promise = self._viewer.scene.open(
  //                 url,
  //                 name,
  //                 { autoSetView: false }
  //               )
  //               Cesium.when(promise, (layers) => {
  //                 if (layers) {
  //                   const realName = []
  //                   layers.forEach((layer) => {
  //                     // if (data2.serviceUrl.indexOf('3D-T0102_XiangMuZhanShiZhuanTiTu_2/rest/realspace/scenes/T0102_%E9%A1%B9%E7%9B%AE%E5%B1%95%E7%A4%BA%E4%B8%93%E9%A2%98%E5%9B%BE_2') !== -1) {
  //                     //   layer.isOverlapDisplayed = false
  //                     // } else {
  //                     //   layer.isOverlapDisplayed = true
  //                     // }
  //                     layer.clearMemoryImmediately = true
  //                     layer.residentRootTile = false
  //                     layer.isOverlapDisplayed = false
  //                     realName.push(layer.name)
  //                     if (layer.imageryProvider) {
  //                       self._viewer.imageryLayers.lowerToBottom(
  //                         layer
  //                       )
  //                     }
  //                   })
  //                   data2.name = realName
  //                   data2.layers = layers
  //                 } else {
  //                   console.error('添加失败')
  //                 }
  //               })
  //             }
  //             break
  //           case 28:
  //             const queryParams = getQueryParams(
  //               data2.serviceUrl
  //             )
  //             console.log(queryParams)
  //             // let mapStyle = ''
  //             // switch (queryParams.T) {
  //             //   case 'img_c':
  //             //     mapStyle = Cesium.TiandituMapsStyle.IMG_C
  //             //     break
  //             //   default:
  //             //     break
  //             // }
  //             self._viewer.scene.imageryLayers.addImageryProvider(
  //               new Cesium.TiandituImageryProvider({
  //                 // mapStyle: mapStyle,
  //                 mapStyle: queryParams.T,
  //                 token: queryParams.tk
  //               }),
  //               0
  //             )
  //             break
  //           default:
  //             break
  //         }
  //         self._viewer.scene.requestRender()
  //         // 如果切换的底图有url
  //         // self._viewer.imageryLayers.addImageryProvider(new Cesium.ArcGisMapServerImageryProvider({
  //         //   url: item.serviceUrl
  //         // }), 0)
  //         // console.log('imageryLayers', self._viewer.scene.imageryLayers._layers)
  //       } else {
  //         // self._viewer.imageryLayers._layers.splice(1, 1)
  //         // console.log('imageryLayers', self._viewer.scene.imageryLayers._layers)
  //       }
  //     },
  //     toggleTerrain(show) {
  //       if (show) {
  //         var url = basemapList[
  //           this.currentIndex
  //         ].resourceMapBaseServiceInfos.filter((item) => {
  //           return item.pkid == this.currentServiceIndex
  //         })[0].terrainUrl
  //         self._viewer.terrainProvider =
  //           new Cesium.CesiumTerrainProvider({
  //             // url: 'https://www.supermapol.com/realspace/services/3D-stk_terrain/rest/realspace/datas/info/data/path',
  //             url: url,
  //             requestWaterMask: true, // 开启法向量
  //             requestVertexNormals: true, // 开启水面特效
  //             isSct: true
  //           })
  //       } else {
  //         self._viewer.terrainProvider =
  //           new Cesium.EllipsoidTerrainProvider({})
  //       }
  //     }
  //   }
  // }

  get terrain() {
    const self = this
    return {
      getList() {
        return self._viewer.baseLayerPicker.viewModel
          .terrainProviderViewModels
      },
      currentIndex: null,
      getCurrentIndex() {
        if (this.currentIndex === null) {
          const current =
            self._viewer.baseLayerPicker.viewModel
              .selectedTerrain
          this.currentIndex = this.getList().findIndex(
            (terrain) => terrain.name === current?.name
          )
        }
        return this.currentIndex
      },
      switch(index) {
        self._viewer.baseLayerPicker.viewModel.selectedTerrain =
          this.getList()[index]
      }
    }
  }

  get mark() {
    const self = this
    let vueComponent = null
    // let currentMode = ''
    let handlerPoint = null
    let handler = null
    return {
      changeMode(mode, component) {
        // currentMode = mode
        if (!vueComponent) {
          vueComponent = component
        }

        if (!handlerPoint) {
          handlerPoint = new Cesium.DrawHandler(
            self._viewer,
            Cesium.DrawMode.Point
          )
          // handlerPoint.activeEvt.addEventListener((isActive) => {
          //   if (isActive === true) {
          //     self._viewer.enableCursorStyle = false
          //     self._viewer._element.style.cursor = ''
          //   } else {
          //     if (currentMode !== '') {
          //       console.log('handlerPoint结束绘制')
          //     }
          //     self._viewer.enableCursorStyle = true
          //   }
          // })
        }
        handlerPoint.activate()
        let drawMode = null
        switch (mode) {
          case 'dian':
            drawMode = Cesium.DrawMode.Point
            break
          case 'xian':
            drawMode = Cesium.DrawMode.Line
            break
          case 'mian':
            drawMode = Cesium.DrawMode.Polygon
            break
          default:
            drawMode = null
            break
        }
        if (drawMode !== null) {
          handlerPoint.clear()
          if (handler) {
            handler.deactivate()
            handler.clear()
          }
          handler = new Cesium.DrawHandler(
            self._viewer,
            drawMode,
            Cesium.ClampMode.Ground
          )
          handler.activeEvt.addEventListener(
            this.handlerActiveEventListener
          )
          handler.drawEvt.addEventListener(
            this.handlerDrawEventListener
          )
          handler.activate()
        } else {
          handlerPoint.deactivate()
          handlerPoint.clear()
          if (handler) {
            handler.deactivate()
            handler.clear()
          }
          handler.activeEvt.removeEventListener(
            this.handlerActiveEventListener
          )
          handler.drawEvt.removeEventListener(
            this.handlerDrawEventListener
          )
          handler = null
        }
      },
      handlerActiveEventListener(isActive) {
        if (isActive === true) {
          self._viewer.enableCursorStyle = false
          self._viewer._element.style.cursor = ''
        } else {
          self._viewer.enableCursorStyle = true
        }
      },
      handlerDrawEventListener(result) {
        if (result.object) {
          vueComponent.showDialog(result.object, true)
          // self._viewer.entities.remove(result.object)
          // const entities = new Cesium.EntityCollection()
          // entities.add(result.object)
          // console.log('entities:', entities)
          // const promise = Cesium.exportKml({ entities: entities })
          // promise.then((e) => {
          //   console.log('kml', e)
          // })
        }
      }
    }
  }

  get cutFill() {
    const self = this
    // 点集合，表示所选范围
    let polygon = [[]]
    let vueComponent = null
    let handlerPoint = null
    let handler = null
    let flat = 0
    return {
      drawArea(component, flatAltitude) {
        if (!vueComponent) {
          vueComponent = component
        }
        if (!handlerPoint) {
          handlerPoint = new Cesium.DrawHandler(
            self._viewer,
            Cesium.DrawMode.Point
          )
        }
        flat = flatAltitude
        handlerPoint.activate()
        handlerPoint.clear()
        this.clear()
        handler = new Cesium.DrawHandler(
          self._viewer,
          Cesium.DrawMode.Polygon,
          Cesium.ClampMode.Ground
        )
        handler.activeEvt.addEventListener(
          this.handlerActiveEventListener
        )
        handler.drawEvt.addEventListener(
          this.handlerDrawEventListener
        )
        handler.activate()
      },
      handlerActiveEventListener(isActive) {
        if (isActive === true) {
          self._viewer.enableCursorStyle = false
          self._viewer._element.style.cursor = ''
        } else {
          self._viewer.enableCursorStyle = true
        }
      },
      handlerDrawEventListener(result) {
        console.log('绘制结果', result)
        polygon = [[]]
        if (result.object.positions) {
          if (result.object.positions.length < 4) {
            if (vueComponent) {
              vueComponent.showMessage(
                'error',
                '请至少绘制四个点'
              )
            }
            return
          }
          const positions = result.object.positions
          positions.push(positions[0])
          positions.forEach((item) => {
            const cartographic =
              Cesium.Cartographic.fromCartesian(item)
            const longitude = Cesium.Math.toDegrees(
              cartographic.longitude
            )
            const latitude = Cesium.Math.toDegrees(
              cartographic.latitude
            )
            polygon[0].push([longitude, latitude])
          })
          console.log('polygon:', polygon)

          // 开始分析
          vueComponent.showLoading()
          const turfPolygon = turf.polygon(polygon)
          const turfExtent = turf.bbox(turfPolygon)
          // 按网格取样，网格间距0.003km
          let turfSamplePoints = turf.pointGrid(
            turfExtent,
            0.003,
            {
              units: 'kilometers',
              mask: turfPolygon
            }
          )
          turfSamplePoints = turf.pointsWithinPolygon(
            turfSamplePoints,
            turfPolygon
          )
          // 转换为cesium取样点
          const cesiumSamplePoints = []
          turfSamplePoints.features.forEach((item) => {
            const coord = item.geometry.coordinates
            cesiumSamplePoints.push(
              Cesium.Cartographic.fromDegrees(
                coord[0],
                coord[1]
              )
            )
          })
          console.log('取样点', cesiumSamplePoints)
          console.log(
            'terrainProvider',
            self._viewer.terrainProvider
          )
          Cesium.when(
            Cesium.sampleTerrain(
              self._viewer.terrainProvider,
              18,
              cesiumSamplePoints
            ),
            (updatedPoints) => {
              console.log('updatePoints', updatedPoints)
              const heights = updatedPoints.map(
                (item) => item.height
              )
              const maxHeight = max(heights) || 0
              const minHeight = min(heights) || 0
              console.log('maxHeight', maxHeight)
              console.log('minHeight', minHeight)
              console.log('flatHeight', flat)
              // 计算大面积和单个取样点面积
              const area = turf.area(turfPolygon).toFixed(3)
              const diffArea =
                area / cesiumSamplePoints.length
              let cut = 0
              let fill = 0
              cesiumSamplePoints.forEach((point) => {
                if ((point.height || 0) > flat) {
                  cut +=
                    ((point.height || 0) - flat) * diffArea
                } else {
                  fill +=
                    (flat - (point.height || 0)) * diffArea
                }
              })
              console.log('挖方', cut)
              console.log('填方', fill)
              vueComponent.result({
                lowestAltitude: minHeight,
                highestAltitude: maxHeight,
                area: area,
                cutVolume: cut,
                fillVolume: fill
              })
              vueComponent.hideLoading()
            }
          )
        }
      },
      clear() {
        if (handler) {
          handler.deactivate()
          handler.clear()
          handler = null
        }
        if (vueComponent) {
          vueComponent.reset()
        }
      }
    }
  }

  get style() {
    return [
      {
        title: '泛光',
        visible: () =>
          !!this._viewer.scene.postProcessStages.bloom
            .enabled,
        set: (flag) => {
          const bloom =
            this._viewer.scene.postProcessStages.bloom
          if (flag) {
            if (!this._style.bloom) {
              bloom.enabled = false
              bloom.uniforms.glowOnly = false
              bloom.uniforms.contrast = 128
              bloom.uniforms.brightness = -0.3
              bloom.uniforms.delta = 1.0
              bloom.uniforms.sigma = 3.78
              bloom.uniforms.stepSize = 5.0
              this._style.bloom = true
            }
            bloom.enabled = true
          } else {
            bloom.enabled = false
          }
        }
      },
      {
        title: '亮度',
        visible: () => !!this._style.BrightnessStage,
        set: (flag) => {
          if (flag) {
            if (!this._style.BrightnessStage) {
              this._style.BrightnessStage =
                this._Cesium.PostProcessStageLibrary.createBrightnessStage()
              this._style.stages.add(
                this._style.BrightnessStage
              )
              this._style.BrightnessStage.uniforms.brightness = 2.0
            }
            this._style.BrightnessStage.enabled = true
          } else {
            if (this._style.BrightnessStage) {
              this._style.stages.remove(
                this._style.BrightnessStage
              )
              this._style.BrightnessStage = undefined
            }
          }
        }
      },
      {
        title: '夜视',
        visible: () => !!this._style.NightVisionStage,
        set: (flag) => {
          if (flag) {
            if (!this._style.NightVisionStage) {
              this._style.NightVisionStage =
                this._Cesium.PostProcessStageLibrary.createNightVisionStage()
              this._style.stages.add(
                this._style.NightVisionStage
              )
            }
            this._style.NightVisionStage.enabled = true
          } else {
            if (this._style.NightVisionStage) {
              this._style.stages.remove(
                this._style.NightVisionStage
              )
              this._style.NightVisionStage = undefined
            }
          }
        }
      },
      {
        title: '黑白',
        visible: () => !!this._style.BlackAndWhiteStage,
        set: (flag) => {
          if (flag) {
            if (!this._style.BlackAndWhiteStage) {
              this._style.BlackAndWhiteStage =
                this._Cesium.PostProcessStageLibrary.createBlackAndWhiteStage()
              this._style.stages.add(
                this._style.BlackAndWhiteStage
              )
            }
            this._style.BlackAndWhiteStage.enabled = true
          } else {
            if (this._style.BlackAndWhiteStage) {
              this._style.stages.remove(
                this._style.BlackAndWhiteStage
              )
              this._style.BlackAndWhiteStage = undefined
            }
          }
        }
      },
      {
        title: '马赛克',
        visible: () => !!this._style.MosaicStage,
        set: (flag) => {
          if (flag) {
            if (!this._style.MosaicStage) {
              this._style.MosaicStage =
                new this._Cesium.PostProcessStage({
                  fragmentShader: mosaicShader
                })
              this._style.stages.add(
                this._style.MosaicStage
              )
            }
            this._style.MosaicStage.enabled = true
          } else {
            if (this._style.MosaicStage) {
              this._style.stages.remove(
                this._style.MosaicStage
              )
              this._style.MosaicStage = undefined
            }
          }
        }
      },
      {
        title: '景深',
        visible: () => !!this._style.DepthOfFieldStage,
        set: (flag) => {
          if (flag) {
            if (!this._style.DepthOfFieldStage) {
              this._style.DepthOfFieldStage =
                this._Cesium.PostProcessStageLibrary.createDepthOfFieldStage()
              const { uniforms } =
                this._style.DepthOfFieldStage
              uniforms.focalDistance = 87 // 焦距
              uniforms.delta = 1
              uniforms.sigma = 3.78
              uniforms.stepSize = 2.46 // 步长
              this._style.stages.add(
                this._style.DepthOfFieldStage
              )
            }
            this._style.DepthOfFieldStage.enabled = true
          } else {
            if (this._style.DepthOfFieldStage) {
              this._style.stages.remove(
                this._style.DepthOfFieldStage
              )
              this._style.DepthOfFieldStage = undefined
            }
          }
        }
      }
    ]
  }

  get weather() {
    if (!this._weather.fog) {
      this._weather.fog = this._viewer.scene.fog
      this._weather.fog.show = false
    }
    return [
      {
        title: '雾',
        icon: 'wu',
        visible: () => {
          return this._weather.fog.show
        },
        set: (flag) => {
          this._weather.fog.density = 0.001
          this._weather.fog.minimumBrightness = 0.8
          this._weather.fog.enabled = flag
          this._weather.fog.show = flag
        }
      },
      {
        title: '雨',
        icon: 'yu',
        visible: () => {
          return !!this._weather.rain
        },
        set: (flag) => {
          if (flag) {
            this._weather.rain =
              new this._Cesium.PostProcessStage({
                fragmentShader: rainShader
              })
            this._viewer.scene.postProcessStages.add(
              this._weather.rain
            )
          } else {
            this._viewer.scene.postProcessStages.remove(
              this._weather.rain
            )
            this._weather.rain = null
          }
        }
      },
      {
        title: '雪',
        icon: 'xue',
        visible: () => {
          return !!this._weather.snow
        },
        set: (flag) => {
          if (flag) {
            this._weather.snow =
              new this._Cesium.PostProcessStage({
                fragmentShader: snowShader
              })
            this._viewer.scene.postProcessStages.add(
              this._weather.snow
            )
          } else {
            this._viewer.scene.postProcessStages.remove(
              this._weather.snow
            )
            this._weather.snow = null
          }
        }
      }
    ]
  }

  get underground() {
    // if (!this._underground) {
    //   this._underground = new mars3d.analysi.Underground({
    //     viewer: this._viewer,
    //     alpha: 1,
    //     enable: false
    //   })
    // }
    // return this._underground
  }

  get scene() {
    return this._viewer.scene
  }

  get canvas() {
    return this._viewer.canvas
  }

  get camera() {
    return this._viewer.camera
  }

  get spaceCameraController() {
    return this._viewer.scene.screenSpaceCameraController
  }
}
